package cn.pomelo.signal.service.impl;

import cn.pomelo.signal.common.Constants;
import cn.pomelo.signal.config.SignalConfig;
import cn.pomelo.signal.mapper.SJobMapper;
import cn.pomelo.signal.model.SJob;
import cn.pomelo.signal.quartZ.DataUpdateJob;
import cn.pomelo.signal.service.SJobService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class SJobServiceImpl implements SJobService {

    @Resource
    private SJobMapper sJobMapper;

    @Resource
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() throws SchedulerException {
        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        scheduler.clear();
        JobDetail jobDetail = JobBuilder.newJob(DataUpdateJob.class)
                .withIdentity("dataUpdate", "dataUpdateGroup").build();
        // 每天下午7点执行
        CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(SignalConfig.getCorn());
//        CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule("* 0/1 * * * ? *");
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("dataUpdateTrigger", "dataUpdateTriggerGroup")
                .startNow()
                .withSchedule(cronSchedule).build();
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }

    @Override
    public int deleteByPrimaryKey(Long jobId) {
        return sJobMapper.deleteByPrimaryKey(jobId);
    }

    @Override
    public int insert(SJob record) {
        return sJobMapper.insert(record);
    }

    @Override
    public int insertSelective(SJob record) {
        return sJobMapper.insertSelective(record);
    }

    @Override
    public SJob selectByPrimaryKey(Long jobId) {
        return sJobMapper.selectByPrimaryKey(jobId);
    }

    @Override
    public int updateByPrimaryKeySelective(SJob record) {
        return sJobMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(SJob record) {
        return sJobMapper.updateByPrimaryKey(record);
    }

    @Override
    public boolean run(Long jobId) throws SchedulerException, InterruptedException {
        System.out.println("run方法");
        SJob temp = selectByPrimaryKey(jobId);
        boolean res = false;
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(Constants.TASK_PROPERTIES, temp);
        JobKey jobKey = JobKey.jobKey(Constants.TASK_CLASS_NAME + temp.getJobId(), temp.getJobGroup());
        if (scheduler.checkExists(jobKey)) {
            res = true;
            scheduler.triggerJob(jobKey);
        }
        TimeUnit.MINUTES.sleep(1);
        return res;
    }

}
